package com.wu.server.websocket;

/**
 * @author Wugs
 * @version 1.0
 * @date 2021/3/2 21:28
 */
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
// 你的WebSocket访问地址
@ServerEndpoint("/tagSales")
public class GoodsTagWebSocket {
    static Session session;
    //定义Websocket容器，储存session
    private static CopyOnWriteArraySet<GoodsTagWebSocket> webSocketSet = new CopyOnWriteArraySet<>();
    //对应前端的一些事件
    //建立连接

    @OnOpen
    public void opOpen(Session session) {
        GoodsTagWebSocket.session = session;
        System.out.println("标签优惠分析连接成功");
    }

    //关闭连接
    @OnClose
    public void onClose() {
        System.out.println("连接关闭");
        webSocketSet.remove(this);
    }
    //发送消息
    public static void sendMessage(String message){
        //遍历储存的Websocket
        try {
            System.out.println("优惠标签发送成功");
            GoodsTagWebSocket.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
